<template>
	<el-upload
		v-model:file-list="fileList"
		class="upload-demo"
		:action="oss.host"
		:data="uploadData"
		:on-preview="handlePreview"
		:on-remove="handleRemove"
		:on-success="handleAvatarSuccess"
		:before-upload="beforeAvatarUpload"
		:multiple="multiple"
		:limit="limit"
		:list-type="listType"
		:accept="accept"
		:on-progress="handleProgress"
		:on-exceed="handleExceed"
	>
		<el-button type="primary">{{ btnName }}</el-button>
	</el-upload>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import store from '@/store'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { BASE_OSS } from '@/config/index'

const prop = defineProps({
	btnName: {
		type: String,
		default: '点击上传图片'
	},
	backProp: {
		type: String,
		default: ''
	},
  multiple: {
		type: Boolean,
		default: false
	},
  limit: {
		type: Number,
		default: 1
	},
	listType: {
		type: String,
		default: 'picture'
	},
	accept: {
		type: String,
		default: 'image/*'
	},
})
const emit = defineEmits(['callback', 'removeImg'])


const oss: any = computed(() => store.appStore.oss)
const uploadData: any = reactive({
	key: '',
	policy: oss.value.policy,
	OSSAccessKeyId: oss.value.accessid,
	success_action_status: 200,
	signature: oss.value.signature,
	callback: oss.value.callback,
	dir: oss.value.dir
})
// // .console.log(uploadData, 'uploadData')

const fileList = ref<UploadUserFile[]>([])

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
	emit('removeImg',{uid:uploadFile.uid})
}

const handlePreview: UploadProps['onPreview'] = (file) => {
	// // .console.log(file)
}
const randomString = (len: any,type: any) => {
	return new Promise((resolve,reject) => {
    let lens = len || 16
    let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    let maxPos = chars.length
    let pwd = ''
    for (let i = 0; i < lens; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    let img = uploadData.dir + pwd+ type
    resolve(img)
  })
}
const beforeAvatarUpload = async (file: any) => {
	let imgType = file.name.slice(file.name.lastIndexOf('.'))
	uploadData.key = await randomString(16,imgType)
  // // .console.log(uploadData.key,'uploadData.key');
	const isLt2M = file.size / 1024 / 1024 < 10
	if (!isLt2M) {
		ElMessage.error('上传图片大小不能超过 10MB!')
	}
	return isLt2M
}
const handleProgress = async (evt:any,uploadFile:any,uploadFiles:any) => {
  // // .console.log(evt.percent.toFixed(2),uploadFile.name);
}
const handleExceed = (files: any, uploadFiles: any) => {
  if(files.length >= prop.limit){
    ElMessage.error(`最多上传${prop.limit}张图片`)
  }else{
    ElMessage.error('上传图片错误，请重试')
  }
}
const handleAvatarSuccess = (res: any, file: any) => {
  if(res.code == 200){
    emit('callback', { img: BASE_OSS + '/' + uploadData.key, backProp: prop.backProp, uid: file.uid})
  }else{
    ElMessage.error(res.data || '上传图片错误，请重试')
  }
}
</script>
